package com.intelligent.eayon.utils;

public class ByteUtils {

    /**
     * short To Bytes
     * @param n short
     * @return byte array
     */
    public static byte[] shortToBytes(short n) {
        byte[] b = new byte[2];
        b[1] = (byte) (n & 0xff);
        b[0] = (byte) ((n >> 8) & 0xff);
        return b;
    }

    /**
     * bytes To Short
     * @param b byte
     * @return short
     */
    public static short bytesToShort(byte[] b) {
        return (short) (b[1] & 0xff
                | (b[0] & 0xff) << 8);
    }

    /**
     * int to byte[]
     * @param num int
     * @return byte[]
     */
    public static byte[] intToBytes(int num) {
        byte[] b = new byte[4];
        for (int i = 0; i < 4; i++) {
            b[i] = (byte) (num >>> (24 - i * 8));
        }
        return b;
    }

    /**
     * bytes to int
     * @param b byte[]
     * @return int
     */
    public static int bytes2int(byte[] b) {
//byte[] b=new byte[]{1,2,3,4};
        int mask = 0xff;
        int temp = 0;
        int res = 0;
        for (int i = 0; i < 4; i++) {
            res <<= 8;
            temp = b[i] & mask;
            res |= temp;
        }
        return res;
    }

    /**
     * long To Bytes
     * @param num long
     * @return byte[]
     */
    public static byte[] longToBytes(long num) {
        byte[] b = new byte[8];
        for (int i = 0; i < 8; i++) {
            b[i] = (byte) (num >>> (56 - i * 8));
        }
        return b;
    }

    /**
     * float To Bytes
     * @param data float
     * @return byte[]
     */
    public static byte[] floatToBytes(float data) {
        int intBits = Float.floatToIntBits(data);
        return intToBytes(intBits);
    }

    /**
     * bytes To Float
     * @param bytes byte[]
     * @return float
     */
    public static float bytesToFloat(byte[] bytes) {
        return Float.intBitsToFloat(bytes2int(bytes));
    }

}
